window.ready = function () {
    //return;
    Custom.init();

    (function () {
        //set cookies start
        var createCookie = function (name, value, days) {
            if (days) {
                var date = new Date();
                date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
                var expires = "; expires=" + date.toGMTString();
            }
            else var expires = "";
            document.cookie = name + "=" + value + expires + "; domain=.; path=/";
        }
        
        var eraseCookie = function (name) {
            createCookie(name, "", -31);
        }

        var setVM = function (vm) {
            eraseCookie("vm");
            createCookie("vm", vm, 30);
        };

        var academicBooksLinks = $$('#academicBooksLinks');
        academicBooksLinks.onclick = function () {
            setVM('a');
        };

        var mobileSiteLink = $$('#mobileSiteLink');
        mobileSiteLink.onclick = function () {
            setVM('m');
        };
        //set cookies end

        //selects
        var browseCategoriesSelect = $$('.list')[0];
        var browseCategoriesTop = $$('.listHeader')[0];
        var focusField = document.createElement('input');
        focusField.type = 'text';
        focusField.className = 'hiddenFocusElement';
        browseCategoriesSelect.style.display = 'none';

        var browseSearchCategoriesSelect = $$('.listSearch')[0];
        var browseSearchCategoriesTop = $$('.listHeaderSearch')[0];
        if (browseSearchCategoriesTop) {
            var focusSearchField = document.createElement('input');
            focusSearchField.type = 'text';
            focusSearchField.className = 'hiddenSearchFocusElement';
            browseSearchCategoriesSelect.style.display = 'none';
        }

        var initSelectFunc = function (listEl, headerEl, focusEl, onclickFunction, onshow, onhide) {

            //init shadow start

            var shadowTemplate = '<div class="menu-shadow-container"><div class="tr top-corner"></div><div class="tl top-corner"></div><div class="br bottom-corner"></div><div class="bl bottom-corner"></div><div class="hover-pointer"></div><div class="top"><div class="bottom"><div class="left"><div class="right"><div class="menu-shadow-inner"><div class="menu-content"></div></div></div></div></div></div></div>';
            var tmpEl = document.createElement('div');
            tmpEl.innerHTML = shadowTemplate;
            tmpEl = tmpEl.getElementsByTagName('div')[0];
            var menuContentEl = $$('.menu-content', tmpEl)[0];
            var menuShadowInnerEl = $$('.menu-shadow-inner', tmpEl)[0];
            listEl.parentNode.insertBefore(tmpEl, listEl);
            listEl.parentNode.removeChild(listEl);
            menuContentEl.appendChild(listEl);

            listEl.style.visibility = 'hidden';
            listEl.style.display = 'block';
            var w = listEl.offsetWidth - 76;
            if (w > 0)
                menuShadowInnerEl.style.width = w + 'px';
            var h = listEl.offsetHeight - 27;
            if (h > 0)
                menuShadowInnerEl.style.height = h + 'px';


            //set margings and position
            var sides = ['Left', 'Right', 'Top', 'Bottom'];
            for (var i = 0; i < sides.length; i++) {
                tmpEl.style['margin' + sides[i]] = (listEl['offset' + sides[i]] || 0) + 'px';
            }
            listEl.style.margin = '0px';

            tmpEl.style.position = listEl.style.position;
            listEl.style.position = 'static';
            listEl.style.visibility = '';
            tmpEl.style.visibility = 'visible';
            tmpEl.style.display = 'none';

            var originalListEl = listEl;
            listEl = tmpEl;
            //init shadow end

            var isSelectVisible = false;

            listEl.parentNode.appendChild(focusEl);

            var changeListVisibilityFunc = function () {
                if (isSelectVisible) {
                    listEl.style.display = 'none';
                    if (onhide) onhide(listEl);
                }
                else {
                    listEl.style.display = 'block';
                    if (onshow) onshow(listEl);
                }
                isSelectVisible = !isSelectVisible;
                return isSelectVisible;
            };

            originalListEl.changeVisibility = changeListVisibilityFunc;

            var onfocus, onclick;
            var onblur = function () {
                //console.log('blur');
                if (isSelectVisible) {
                    isSelectVisible = false;
                    listEl.style.display = 'none';
                    if (onhide) onhide(listEl);
                }
            };
            onclick = function () {
                //console.log('click');
                if (changeListVisibilityFunc()) {
                    focusEl.focus();
                }
                return false;
            };
            onfocus = function () {
                //console.log('focus');
                if (!isSelectVisible) {
                    changeListVisibilityFunc();
                }
            };
            headerEl.onclick = onclick;
            focusEl.onfocus = onfocus;
            headerEl.onmouseout = function () {
                //console.log('onmouseout');
                focusEl.onblur = onblur;
            };
            headerEl.onmouseover = function () {
                //console.log('onmouseover');
                if (isSelectVisible)
                    focusEl.focus();
                focusEl.onblur = null;
            };
            listEl.onmouseout = function () {
                //console.log('onmouseout');
                focusEl.onblur = onblur;
            };
            listEl.onmouseover = function () {
                //console.log('onmouseover');
                if (isSelectVisible)
                    focusEl.focus();
                focusEl.onblur = null;
            };
            listEl.onscroll = function () {
                //console.log('onscroll');
                if (isSelectVisible)
                    focusEl.focus();
            };
            listEl.onclick = onclickFunction;
        };

        var chouseSubjectFunc = function (e) {
            var e = e || event;
            var el = e.target || e.srcElement;
            if (el.tagName == 'LI') {
                var subjectEl = $$('input', el)[0];
                if (subjectEl)
                    window.open($$.serverURI + '/Category.aspx?CateID=' + subjectEl.value, '_top');
                el.parentNode.changeVisibility();
            }
        };

        var chouseSearchSubjectFunc = function (e) {
            var e = e || event;
            var el = e.target || e.srcElement;
            if (el.tagName == 'LI') {
                var subjectId = $$('input', el)[0].value;
                //window.open('/subjects/subjects.asp?SID=' + subjectId, '_top');
                //focusSearchField.setAttribute('value', subjectId);
                var browseSearchCategoriesTopSpan = $$('span', browseSearchCategoriesTop)[0];
                browseSearchCategoriesTopSpan.innerHTML = el.childNodes[1].nodeValue;
                browseSearchCategoriesSelect.style.display = 'none';
                $$('.search-button', browseSearchCategoriesTop.parentNode)[0].onclick = function () {
                    window.open($$.serverURI + '/subjects/subjects.asp?SID=' + subjectId, '_top');
                };
            }
        };

        //more link
        var moreSubjectsLink = $$('#moreSubjectsLink');
        if (moreSubjectsLink) {
            var bottomCategoriesSelect = browseCategoriesSelect.cloneNode(true);
            var bottomFocusField = focusField.cloneNode(true);
            moreSubjectsLink.parentNode.appendChild(bottomCategoriesSelect);
            moreSubjectsLink.parentNode.appendChild(bottomFocusField);
            initSelectFunc(bottomCategoriesSelect, moreSubjectsLink, bottomFocusField, chouseSubjectFunc,
            function (selEl) { //onshow
                var totalOffsetTop = 0;
                var offsetParent = selEl;
                selEl.style.marginTop = 0;
                while (offsetParent && offsetParent.offsetParent) {
                    totalOffsetTop += offsetParent.offsetTop;
                    offsetParent = offsetParent.offsetParent;
                }
                if (document.documentElement.scrollTop + selEl.offsetWidth > totalOffsetTop) {
                    selEl.style.marginTop = document.documentElement.scrollTop - totalOffsetTop + 'px';
                }
                else
                    selEl.style.marginTop = '';
            },
            function (selEl) { //onhide
                selEl.style.marginTop = '';
            });
        }

        initSelectFunc(browseCategoriesSelect, browseCategoriesTop, focusField, chouseSubjectFunc);
        if (browseSearchCategoriesTop) {
            initSelectFunc(browseSearchCategoriesSelect, browseSearchCategoriesTop, focusSearchField, null);
        }

        //zone select
        var zoneLink = $$('#portalZoneFlag');
        var zoneSelect = $$('#portalZoneSelect');
        var zoneFocusField = focusField.cloneNode(true);
        zoneSelect.parentNode.appendChild(zoneFocusField);
        initSelectFunc(zoneSelect, zoneLink, zoneFocusField, function (e) {
            var e = e || event;
            var el = e.target || e.srcElement;
            if (el.tagName == 'LI') {

                var zoneCode = $$('input', el)[0].value;
                if (zoneCode == "0") {
                    alert("Please select a valid location");
                    return false;
                }
                else {
                    eraseCookie("cc");
                    createCookie("cc", zoneCode, 30);
                    //window.location.reload();

                    var url = window.location.href;
                    if (url.indexOf('#') > 0)
                        url = url.substr(0, url.indexOf('#'));
                    var old = "";
                    url.match(/\?(.+)$/);
                    var params = RegExp.$1;
                    // split up the query string and store in an
                    // associative array
                    var params = params.split("&");
                    var queryStringList = {};

                    for (var i = 0; i < params.length; i++) {
                        var tmp = params[i].split("=");
                        if (tmp[0].toLowerCase() == "countrycode") {
                            old = unescape(tmp[1]);
                        }
                    }

                    url = url.replace("countryCode=" + old.toUpperCase(), "countryCode=" + zoneCode.toUpperCase());
                    url = url.replace("countryCode=" + old.toLowerCase(), "countryCode=" + zoneCode.toLowerCase());
                    window.location.href = url;
                    el.parentNode.changeVisibility();
                }
            }
        });


        (function () {
            var imgToLoad = $$('.img-lazy-load');
            for (var i = 0; i < imgToLoad.length; i++)
                $$.ImgLazyLoad(imgToLoad[i]);
        })();

    })();
    
    //help window start
    (function () {
        var detect = navigator.userAgent.toLowerCase();
        var checkIt = function (string) { return detect.indexOf(string) + 1; }
        var helpPop = function (url) {
            var winH = 624;
            var winW = 980;
            if (checkIt('safari') || checkIt('msie'))
                winH = 625;
            window.open(url, "ebooksHelp", 'height=' + winH + ',width=' + winW + ',status=yes,toolbar=no,menubar=no,location=no,scrolling=no');
        };
        var helpLink = $$('#helpLink');
        if (helpLink)
            helpLink.onclick = function () {
                helpPop(helpLink.href);
                return false;
            };
    })();
    //help window end

    //bestsellers start
    (function () {
        var bestsellersEl = $$('#bestSellers');
        if (bestsellersEl) {

            bestsellersEl.widget =
	        {
	            linksPattern: 'bestsellersLinks_',
	            linksTagName: 'A',
	            contentPattern: 'bestsellersContent_',
	            contentTagName: 'LI',
	            selectedContentEl: null,
	            selectedSubjectEl: null
	        };

            //find shown content element
            var els = $$(bestsellersEl.widget.contentTagName, bestsellersEl);
            for (var i = 0; i < els.length; i++) {
                if (els[i].tagName == bestsellersEl.widget.contentTagName && els[i].id.indexOf(bestsellersEl.widget.contentPattern) != -1 && els[i].style.display != 'none') {
                    bestsellersEl.widget.selectedContentEl = els[i];
                    var subjectElement = $$("#" + els[i].id.replace(bestsellersEl.widget.contentPattern, bestsellersEl.widget.linksPattern));
                    if (subjectElement) {
                        bestsellersEl.widget.selectedSubjectEl = subjectElement;
                        subjectElement.className = 'selected';
                    }
                    break;
                }
            }


            bestsellersEl.onmouseover = function (e) {
                var ev = e || event;
                var el = ev.target || ev.srcElement;
                if (el.tagName == bestsellersEl.widget.linksTagName && el.id.indexOf(bestsellersEl.widget.linksPattern) != -1) {
                    if (bestsellersEl.widget.selectedSubjectEl == el)
                        return false;
                    el.className = 'selected';
                    if (bestsellersEl.widget.selectedSubjectEl)
                        bestsellersEl.widget.selectedSubjectEl.className = '';
                    if (bestsellersEl.widget.selectedContentEl)
                        bestsellersEl.widget.selectedContentEl.style.display = 'none';
                    bestsellersEl.widget.selectedSubjectEl = el;
                    var contentElement = $$("#" + el.id.replace(bestsellersEl.widget.linksPattern, bestsellersEl.widget.contentPattern));
                    if (contentElement) {
                        contentElement.style.display = 'block';
                        bestsellersEl.widget.selectedContentEl = contentElement;
                    }
                }
            };
        }
    })();
    //bestsellers end

    //google analytics start
    (function () {
        window._gaq = window._gaq || [];
        _gaq.push(['_setAccount', 'UA-2325867-1']);
        _gaq.push(['_setDomainName', '.ebooks.com']);
        _gaq.push(['_setAllowHash', false]);
        _gaq.push(['_trackPageview']);
        _gaq.push(['_trackPageLoadTime']);

        if (window.GACommerceFunc)
            window.GACommerceFunc(_gaq);

        var ga = document.createElement('script');
        ga.type = 'text/javascript';
        ga.async = true;
        //ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
        ga.src = 'Scripts/ga.js';
        var s = $$('script')[0]; s.parentNode.insertBefore(ga, s);
    })();
    //google analytics start

    //tabs start
    (function () {
        var currentActiveTab;
        var currentActiveContent;
        for (var i = 1; i <= 5; i++) {
            (function () {
                var tabContentHeader = $$('#tabContentHeader_' + i);
                var tabContent = $$('#tabContent_' + i);

                if (!tabContentHeader || !tabContent)
                    return;

                var index = i; //lock context
                if (tabContentHeader.className == 'active') {
                    currentActiveTab = tabContentHeader;
                    currentActiveContent = tabContent;
                    currentActiveTab.slider = new ebSlider('sliderTab' + i, 'sliderTab' + i + '_bl', 'sliderTab' + i + '_br');
                    currentActiveContent.slider = currentActiveTab.slider;
                }
                tabContentHeader.onclick = function () {
                    if (tabContent == currentActiveContent)
                        return false;
                    tabContent.style.display = 'block';
                    currentActiveContent.style.display = 'none';

                    if (!tabContent.slider || !tabContentHeader.slider) {
                        tabContent.slider = new ebSlider('sliderTab' + index, 'sliderTab' + index + '_bl', 'sliderTab' + index + '_br');
                        tabContentHeader.slider = tabContent.slider;
                    }

                    tabContentHeader.className = 'active';
                    currentActiveTab.className = '';

                    currentActiveTab = tabContentHeader;
                    currentActiveContent = tabContent;
                    return false;
                }
            })();
        }
    })();
    //tabs end

    //tabsFeed start
    (function () {
        var currentFeedActiveTab;
        var currentFeedActiveContent;
        for (var j = 1; j <= 5; j++) {
            (function () {

                var tabFeedContentHeader = $$('#tabFeedContentHeader_' + j);
                var tabFeedContent = $$('#tabFeedContent_' + j);

                if (tabFeedContentHeader) {

                    tabFeedContentHeader.onclick = function () {
                        if (tabFeedContent == currentFeedActiveContent)
                            return false;
                        $$.RemoveClassName(tabFeedContent, 'hidden');
                        if (currentFeedActiveContent)
                            $$.AddClassName(currentFeedActiveContent, 'hidden');

                        $$.AddClassName(tabFeedContentHeader, 'active');
                        if (currentFeedActiveTab)
                            $$.RemoveClassName(currentFeedActiveTab, 'active');

                        currentFeedActiveTab = tabFeedContentHeader;
                        currentFeedActiveContent = tabFeedContent;
                        return false;
                    }

                }

            })();
        }
    })();
    //tabsFeed end

    (function () {
        function positionBlock(elem, x, y) {
            var top = y - 40;
            var left = x + 10;
            elem.style.position = 'absolute';
            elem.style.display = 'block';
            elem.style.top = top + 'px';
            elem.style.left = left + 'px';
        };

        function addEvent(elem, evType, fn) {
            if (typeof (elem) == 'array' || elem.length) {
                var fns = [];
                for (var i = 0; i < elem.length; i++)
                    fns.push(addEvent(elem[i], evType, fn));
                return fns;
            }
            if (elem.addEventListener) {
                elem.addEventListener(evType, fn, false);
                return fn;
            }
            else {
                var iefn = function () {
                    fn.call(elem);
                };
                elem.attachEvent('on' + evType, iefn);
                return iefn;
            }
        };

        var hoveredItem = {};
        var overAction = function (e) {
            var e = e || window.event;
            var element = e.target || e.srcElement;
            var isHideAction = false;
            if (element.tagName != 'IMG' || !$$.HasClassName(element, 'img-hover-action'))
                isHideAction = true;

            if (!isHideAction) {
                var container = element;
                while (container && container.tagName != 'LI') {
                    container = container.parentNode;
                }

                if (hoveredItem.element != container) {
                    //calculate absolute offsets (if item has class 'moving' position is old)
                    if (!hoveredItem.element || !$$.HasClassName(element, 'moving')) {
                        var offsetParent = element;
                        var totalOffsetLeft = 0;
                        var totalOffsetTop = 0;
                        while (offsetParent && offsetParent.offsetParent) {
                            totalOffsetLeft += offsetParent.offsetLeft;
                            totalOffsetTop += offsetParent.offsetTop;
                            offsetParent = offsetParent.offsetParent;
                        }

                        hoveredItem.left = totalOffsetLeft;
                        hoveredItem.top = totalOffsetTop;
                        hoveredItem.bottom = totalOffsetTop + element.offsetHeight;
                        hoveredItem.right = totalOffsetLeft + element.offsetWidth;
                    }

                    //test div
                    //                                    var div = document.createElement('div');
                    //                                    div.innerHTML = '1234';
                    //                                    document.body.appendChild(div);
                    //                                    div.style.position = 'absolute';
                    //                                    div.style.background = 'red';
                    //                                    div.style.height = element.offsetHeight + 'px';
                    //                                    div.style.width = element.offsetWidth + 'px';
                    //                                    div.style.top = totalOffsetTop + 'px';
                    //                                    div.style.left = totalOffsetLeft + 'px';
                    //                                    div.style.zIndex = 99;
                    //test div

                    var copyBox = $$('.hover-box', container);
                    if (!copyBox || copyBox.length == 0)
                        return;
                    var data = copyBox[0].innerHTML
                    var hoverBlock = $$('#hoverBlock');
                    var hoverBlockInner = $$('#hoverBlockInner');
                    hoverBlockInner.innerHTML = data;
                    hoveredItem.hoverBlock = hoverBlock;
                    hoveredItem.element = container;
                }

                if (e.pageX == null && e.clientX != null) {
                    var html = document.documentElement;
                    var body = document.body;
                    e.pageX = e.clientX + (html && html.scrollLeft || body && body.scrollLeft || 0) - (html.clientLeft || 0);
                    e.pageY = e.clientY + (html && html.scrollTop || body && body.scrollTop || 0) - (html.clientTop || 0);
                }

                var x = e.pageX;
                var y = e.pageY;

                if (isMouseUnderImage(x, y)) {
                    positionBlock(hoveredItem.hoverBlock, hoveredItem.right + 10, y);
                }
                else {
                    outAction();
                }
            }
            else {
                outAction();
            }

        };

        var isMouseUnderImage = function (x, y) {
            if (x < hoveredItem.left || x > hoveredItem.right ||
                y < hoveredItem.top || y > hoveredItem.bottom)
                return false;
            return true;
        };

        var outAction = function () {
            var hoverBlock = $$('#hoverBlock');
            var hoverBlockInner = $$('#hoverBlockInner');
            hoverBlockInner.innerHTML = '';
            hoverBlock.style.display = '';
            hoverBlock.style.top = '-1000px';
            hoverBlock.style.left = '-1000px';
            hoveredItem = {};
        };

        //        var elements = $$('.slider-hover-action');
        //        for (var i = 0; i < elements.length; i++) {
        //            //var element = elements[i].getElementsByTagName('li');
        //            //for (var j = 0; j < element.length; j++) {
        //            addEvent(elements[i], 'mouseover', overAction);
        //            addEvent(elements[i], 'mousemove', overAction);
        //            //addEvent(element[j], 'mouseout', outAction);
        //            //}
        //        }
        //        addEvent($$('#hoverBlock'), 'mouseover', overAction);
        $$.AddEvent($$('body'), 'mouseover', overAction);
        $$.AddEvent($$('body'), 'mousemove', overAction);
    })();

    (function () {

        //homepage top 5
        var staffPicksLinkContainer = $$('#staffPicksLinks');
        if (staffPicksLinkContainer) {
            var staffPicksSlider = new autoSlider('sliderHomePageTop5');
            var staffPicksHeader = $$('.title', $$('.staff-pick')[0])[0];
            var staffPicksContainer = $$('.staff-pick')[0];
            var margin = -29;
            var minMargin = -29;
            var showHideInterval = 50;
            var direction;
            var timeoutId;
            staffPicksContainer.onmouseover = function () {
                direction = 'down';
                var downFunc = function () {
                    if (direction == 'down')
                        if (margin < 0) {
                            margin += 3;
                            if (margin > 0)
                                margin = 0;
                            staffPicksHeader.style.marginTop = margin + 'px';
                            timeoutId = setTimeout(downFunc, showHideInterval)
                        }
                };
                timeoutId = setTimeout(downFunc, showHideInterval);
            };
            staffPicksContainer.onmousemove = function () {
                staffPicksContainer.onmouseover();
            };

            var offsetParent = staffPicksContainer;
            var totalOffsetLeft = 0;
            var totalOffsetTop = 0;
            while (offsetParent && offsetParent.offsetParent) {
                totalOffsetLeft += offsetParent.offsetLeft;
                totalOffsetTop += offsetParent.offsetTop;
                offsetParent = offsetParent.offsetParent;
            }

            var hoveredItem = {};
            hoveredItem.left = totalOffsetLeft;
            hoveredItem.top = totalOffsetTop;
            hoveredItem.bottom = totalOffsetTop + staffPicksContainer.offsetHeight;
            hoveredItem.right = totalOffsetLeft + staffPicksContainer.offsetWidth;

            $$.AddEvent($$('body'), 'mouseover', function (e) {
                e = e || event;
                var el = e.target || e.srcElement;
                var parent = el.parentNode;

                if (e.pageX == null && e.clientX != null) {
                    var html = document.documentElement;
                    var body = document.body;
                    e.pageX = e.clientX + (html && html.scrollLeft || body && body.scrollLeft || 0) - (html.clientLeft || 0);
                    e.pageY = e.clientY + (html && html.scrollTop || body && body.scrollTop || 0) - (html.clientTop || 0);
                }

                var x = e.pageX;
                var y = e.pageY;

                if (x <= hoveredItem.left || x >= hoveredItem.right || y <= hoveredItem.top || y >= hoveredItem.bottom) {
                    //if (el == staffPicksContainer) {
                    direction = 'up';
                    var upFunc = function () {
                        if (direction == 'up')
                            if (margin > minMargin) {
                                margin -= 3;
                                if (margin < minMargin)
                                    margin = minMargin;
                                staffPicksHeader.style.marginTop = margin + 'px';
                                timeoutId = setTimeout(upFunc, showHideInterval);
                            }
                    };
                    timeoutId = setTimeout(upFunc, showHideInterval);
                }
            });

            var staffPicksSliderIsLocked = false;
            var links = $$("a", staffPicksLinkContainer);
            var activeLink;
            staffPicksSlider.onReady = function (currentSlideNumber) {
                if (activeLink)
                    activeLink.className = '';
                try {
                    links[currentSlideNumber - 1].className = 'active';
                } catch(err) {}
                activeLink = links[currentSlideNumber - 1];
                staffPicksSliderIsLocked = false;
            };
            for (var i = 0; i <= Math.max(staffPicksSlider.numberOfSlides - 1, links.length - 1); i++) {
                (function () {
                    var link = links[i];
                    if (staffPicksSlider.numberOfSlides - 1 < i) //hide link
                    {
                        link.style.display = 'none';
                        return;
                    }
                    if (link) {
                        if (i == 0)
                            activeLink = link;
                        var index = i + 1;
                        link.onclick = function () {
                            if (staffPicksSliderIsLocked)
                                return false;
                            staffPicksSliderIsLocked = true;
                            if (!staffPicksSlider.GoTo(index))
                                staffPicksSliderIsLocked = false;
                            staffPicksSlider.ResetTimer();
                            activeLink.className = '';
                            link.className = 'active';
                            activeLink = link;
                            return false;
                        };
                    }

                })();
            }
        }

        var slidersElements = $$('.slider-init');
        if (slidersElements && slidersElements.length) {
            for (var i = 0; i < slidersElements.length; i++) {
                var sliderMainContainer = slidersElements[i].parentNode.parentNode;
                if (sliderMainContainer) {
                    var leftArrow = $$('.slider-button-left', sliderMainContainer)[0];
                    var rightArrow = $$('.slider-button-right', sliderMainContainer)[0];
                    if (slidersElements[i] && leftArrow && rightArrow)
                        new ebSlider(slidersElements[i], leftArrow, rightArrow);
                }
            }
        }

        //var t = new ebSlider('sliderHomePageTop5', 'sliderFeaturedTitles_bl', 'sliderFeaturedTitles_br');
        //var t = new ebSlider('sliderFeaturedTitles', 'sliderFeaturedTitles_bl', 'sliderFeaturedTitles_br');
        //self-help books
        //var t = new ebSlider('sliderSelfHelpBooks', 'sliderSelfHelpBooks_bl', 'sliderSelfHelpBooks_br');
        //NewYork times bestsellers
        //var t = new ebSlider('sliderNewYorkTimes', 'sliderNewYorkTimes_bl', 'sliderNewYorkTimes_br');
        //var t = new ebSlider('sliderNewYorkTimesPreview', 'sliderNewYorkTimes_bl', 'sliderNewYorkTimes_br');
        //Recently Reduced Titles
        //var t = new ebSlider('sliderRecentlyReducedTitles', 'sliderRecentlyReducedTitles_bl', 'sliderRecentlyReducedTitles_br');
        //Featured author
        //var t = new ebSlider('sliderFeaturedAuthor', 'sliderFeaturedAuthor_bl', 'sliderFeaturedAuthor_br');
    })();

};

function autoSlider(containerId) {
    this.curentSlideNumber = 1;
    this.timeOut = 10000;
    this.imgs = $$('img', $$('#' + containerId));
    $$.AddClassName(this.imgs, 'moving');
    var slider = this;
    this.slider = new ebSlider(containerId);
    this.slider.onReady = function () {
        if (slider.onReady)
            slider.onReady(slider.curentSlideNumber);
    };
    this.numberOfSlides = this.slider.itemCnt;

    setTimeout(function () {
        var hiddenImages = $$('.img-lazy-load-i', $$('#' + containerId));
        for (var i = 0; i < hiddenImages.length; i++)
            $$.ImgLazyLoad(hiddenImages[i]);
    }, this.timeOut);
    
    this.intervalId = setInterval(function () {
        slider.Go(1);
    }, this.timeOut);
};
autoSlider.prototype.GoTo = function (slideNumber) {
    var slidesBetweenDirectWay = slideNumber - this.curentSlideNumber;
    if (slidesBetweenDirectWay > 0 && slidesBetweenDirectWay != 1)
        return this.Go(-this.numberOfSlides + slidesBetweenDirectWay);
    else
        return this.Go(slidesBetweenDirectWay);
};
autoSlider.prototype.ResetTimer = function (slideNumber) {
    clearInterval(this.intervalId);
    var slider = this;
    this.intervalId = setInterval(function () {
        slider.Go(1);
    }, this.timeOut);
};
autoSlider.prototype.Go = function (step) {
    this.curentSlideNumber += step;
    if (this.curentSlideNumber > this.numberOfSlides)
        this.curentSlideNumber -= this.numberOfSlides;
    if (this.curentSlideNumber < 1)
        this.curentSlideNumber += this.numberOfSlides;
    if (step == 0)
        return false;
    this.slider.Go(-step);
    return true;
};

    function ebSlider(containerId, btLeftId, btRightId) {
        this.cntr = typeof (containerId) == 'string' ? $$("#" + containerId) : containerId;
        this.btLeft = typeof (btLeftId) == 'string' ? $$("#" + btLeftId) : btLeftId;
        this.brRight = typeof (btRightId) == 'string' ? $$("#" + btRightId) : btRightId;
        if (this.cntr) {
            var sliderContainer = this.cntr.parentNode.parentNode;
            sliderContainer.onmousemove = function () {
                sliderContainer.onmousemove = null;
                var hiddenImages = $$('.img-lazy-load-i', sliderContainer);
                for (var i = 0; i < hiddenImages.length; i++)
                    $$.ImgLazyLoad(hiddenImages[i]);
            }
        }
        this.items = [];
        var tUl = $$("ul", this.cntr)[0];
        var tElems = $$("li", this.cntr);

        this.itemWidth = (this.items && this.items.length > 1 ? tElems[1].offsetLeft - tElems[0].offsetLeft : tElems[0].offsetWidth);

        this.itemCnt = tElems.length;
        this.options = { timerstep: 13, shifttime: 400 };

        var cntrLeft = $$.GetStyle(this.cntr, "paddingLeft");
        cntrLeft = cntrLeft ? parseInt(cntrLeft) : 0;
        var cStyle = this.cntr.style;
        cStyle.width = $$.GetInnerWidth(this.cntr) + "px";
        //cStyle.position = "absolute";
        cStyle.left = cntrLeft + "px";
        cStyle.paddingLeft = "0px";
        cStyle.paddingRight = "0px";
        this.numItemsVisible = this.cntr.offsetWidth / this.itemWidth;

        if (this.btLeft && this.brRight && tElems.length <= Math.round(this.numItemsVisible)) {
            $$.AddClassName([this.btLeft, this.brRight], 'hidden');
        }

        tUl.style.width = this.itemWidth * tElems.length + 10 + "px";

        var needDouble = this.numItemsVisible < this.itemCnt;
        for (var i = this.itemCnt >>> 0; i--; ) {
            tElems[i].style.position = "absolute";
            tElems[i].style.left = i * this.itemWidth + "px";
            this.items[i] = tElems[i];
            if (needDouble) {
                var node = tElems[i].cloneNode(true);
                node.style.left = (this.itemCnt + i) * this.itemWidth + "px";
                tUl.appendChild(node);
                this.items[this.itemCnt + i] = node;
            }
        }
        if (needDouble) {
            var item = this.items.splice(this.items.length - 1, 1);
            this.items.splice(0, 0, item[0]);
            this.items[0].style.left = (-this.itemWidth) + "px"
        }

        var self = this;

        if (this.btLeft) {
            var currentLH = this.btLeft.onclick;
            this.btLeft.onclick = function (e) {
                if (currentLH) currentLH(e);
                self.Go(1);
            };
        }
        if (this.brRight) {
            var currentRH = this.brRight.onclick;
            this.brRight.onclick = function (e) {
                if (currentRH) currentRH(e);
                self.Go(-1);
            };
        }
    };
    

    // function designed for 1 step only
    ebSlider.prototype.Go = function (step) {
        var items = this.items;
        step %= items.length;
        // if some items are not visible
        if (!this.siP || !this.siP.asyncId) {
            if (this.numItemsVisible < items.length) {
                if (step > 0) {
                    for (var i = 0; i < step; i++) {
                        var item = items.splice(items.length - 1, 1);
                        items.splice(0, 0, item[0]);
                        items[0].style.left = parseInt(items[1].style.left) - this.itemWidth + "px";
                    }
                    this.ShiftItems(step * this.itemWidth);
                } else {
                    for (var i = 0; i > step; i--) {
                        var item = this.items.splice(0, 1);
                        items.splice(this.items.length, 0, item[0]);
                        items[items.length - 1].style.left = parseInt(items[items.length - 2].style.left) + this.itemWidth + "px";
                    }
                    this.ShiftItems(step * this.itemWidth);
                }
            }
        }
        //   	else {
        //   		if (step * this.shiftParams.totalOffset > 0) {
        //   			this.shiftParams.totalOffset += (step > 0 ? this.itemWidth : -this.itemWidth);
        //   		}
        //   	}
    };

    ebSlider.prototype.ShiftItems = function (offset) {
        var self = this;
        var tDate = new Date().getTime();
        this.siP = {
            totalOffset: offset,
            offset: 0,
            shiftBase: parseInt(this.items[0].style.left),
            dateStart: tDate,
            dateRatio: offset / this.options.shifttime
        };

        var tFunc = function () {
            if (Math.abs(self.siP.totalOffset) > Math.abs(self.siP.offset)) {
                var ticks = new Date().getTime() - self.siP.dateStart;
                var tOffset = ticks * self.siP.dateRatio;
                self.siP.offset = Math.abs(tOffset) > Math.abs(self.siP.totalOffset) ? self.siP.totalOffset : tOffset;
                for (var i = 0; i < self.items.length; i++) {
                    self.items[i].style.left = self.siP.shiftBase + i * self.itemWidth + self.siP.offset + "px";
                }
                self.siP.asyncId = setTimeout(tFunc, 30);
            } else {
                clearTimeout(self.siP.asyncId);
                self.siP.asyncId = null;
                if (self.onReady)
                    self.onReady();
            }
        };
        tFunc();
    };

    /* Custom checkbox, radiobutton and select */
    var checkboxHeight = "25";
    var radioHeight = "25";
    var selectWidth = "190";

    document.write('<style type="text/css">input.styled { display: none; } select.styled {height:25px; position: relative; width: ' + selectWidth + 'px; opacity: 0; filter: alpha(opacity=0); z-index: 5; } .disabled { opacity: 0.5; filter: alpha(opacity=50); }</style>');

    var Custom = {
        refresh: function () {
            var inputsElemnts = document.getElementsByTagName("input");
            for (var a = 0; a < inputsElemnts.length; a++) {
                if ((inputsElemnts[a].type == "checkbox" || inputsElemnts[a].type == "radio") && inputsElemnts[a].className == "styled") {

                    var spanElement1 = document.getElementById(inputsElemnts[a].id + '-span');

                    if (spanElement1 == null) {
                        return;
                    }

                    var position;

                    if (inputsElemnts[a].checked == true) {
                        position = "0 -" + (checkboxHeight * 2) + "px";
                        spanElement1.style.backgroundPosition = position;
                    } else {
                        spanElement1.style.backgroundPosition = "0 0px";
                    }
                    inputsElemnts[a].onchange = Custom.clear;
                    if (!inputsElemnts[a].getAttribute("disabled")) {
                        spanElement1.onmousedown = Custom.pushed;
                        spanElement1.onmouseup = Custom.check;
                    } else {
                        spanElement1.className = span[a].className += " disabled";
                    }
                }
            }
        },
        init: function () {
            var inputs = document.getElementsByTagName("input"), span = Array(), textnode, option, active;
            for (a = 0; a < inputs.length; a++) {
                if ((inputs[a].type == "checkbox" || inputs[a].type == "radio") && inputs[a].className == "styled") {

                    var spanElement = null;

                    if (inputs[a].id != null && inputs[a].id != "") {
                        spanElement = document.getElementById(inputs[a].id + '-span');
                    }

                    if (spanElement == null) {
                        spanElement = document.createElement('span');
                        spanElement.className = inputs[a].type;

                        if (inputs[a].id != null && inputs[a].id != "") {
                            spanElement.id = inputs[a].id + '-span';
                        }
                    }

                    span[a] = spanElement;

                    var position;

                    if (inputs[a].checked == true) {
                        if (inputs[a].type == "checkbox") {
                            position = "0 -" + (checkboxHeight * 2) + "px";
                            span[a].style.backgroundPosition = position;
                        } else {
                            position = "0 -" + (radioHeight * 2) + "px";
                            span[a].style.backgroundPosition = position;
                        }
                    }
                    inputs[a].parentNode.insertBefore(span[a], inputs[a]);
                    inputs[a].onchange = Custom.clear;
                    if (!inputs[a].getAttribute("disabled")) {
                        span[a].onmousedown = Custom.pushed;
                        span[a].onmouseup = Custom.check;
                    } else {
                        span[a].className = span[a].className += " disabled";
                    }
                }
            }

            inputs = document.getElementsByTagName("select");
            for (var a = 0; a < inputs.length; a++) {
                if (inputs[a].className == "styled") {
                    option = inputs[a].getElementsByTagName("option");
                    active = option[0].childNodes[0].nodeValue;
                    textnode = document.createTextNode(active);
                    for (b = 0; b < option.length; b++) {
                        if (option[b].selected == true) {
                            textnode = document.createTextNode(option[b].childNodes[0].nodeValue);
                        }
                    }
                    span[a] = document.createElement("span");
                    span[a].className = "select";
                    span[a].id = "select" + inputs[a].name;
                    span[a].appendChild(textnode);
                    inputs[a].parentNode.insertBefore(span[a], inputs[a]);
                    span[a].style.width = inputs[a].offsetWidth + "px";
                    inputs[a].style.width = span[a].offsetWidth + "px";
                    if (!inputs[a].getAttribute("disabled")) {
                        inputs[a].onchange = Custom.choose;
                    } else {
                        inputs[a].previousSibling.className = inputs[a].previousSibling.className += " disabled";
                    }
                }
            }
            $$.AddEvent(document, 'onmouseup', Custom.clear);
        },
        pushed: function () {
            var element = this.nextSibling;
            if (element.checked == true && element.type == "checkbox") {
                this.style.backgroundPosition = "0 -" + checkboxHeight * 3 + "px";
            } else if (element.checked == true && element.type == "radio") {
                this.style.backgroundPosition = "0 -" + radioHeight * 3 + "px";
            } else if (element.checked != true && element.type == "checkbox") {
                this.style.backgroundPosition = "0 -" + checkboxHeight + "px";
            } else {
                this.style.backgroundPosition = "0 -" + radioHeight + "px";
            }
        },
        check: function () {
            var element = this.nextSibling;
            if (element.checked == true && element.type == "checkbox") {
                this.style.backgroundPosition = "0 0";
                $$.RemoveClassName(element, 'checked');
                element.checked = false;
            } else {
                if (element.type == "checkbox") {
                    this.style.backgroundPosition = "0 -" + checkboxHeight * 2 + "px";
                } else {
                    this.style.backgroundPosition = "0 -" + radioHeight * 2 + "px";
                    var group = this.nextSibling.name;
                    var inputs = document.getElementsByTagName("input");
                    for (var a = 0; a < inputs.length; a++) {
                        if (inputs[a].name == group && inputs[a] != this.nextSibling) {
                            inputs[a].previousSibling.style.backgroundPosition = "0 0";
                        }
                    }
                }
                element.checked = true;
                $$.AddClassName(element, 'checked');
            }
        },
        clear: function () {
            var inputs = document.getElementsByTagName("input");
            for (var b = 0; b < inputs.length; b++) {
                if (inputs[b].type == "checkbox" && inputs[b].checked == true && inputs[b].className == "styled") {
                    inputs[b].previousSibling.style.backgroundPosition = "0 -" + checkboxHeight * 2 + "px";
                } else if (inputs[b].type == "checkbox" && inputs[b].className == "styled") {
                    inputs[b].previousSibling.style.backgroundPosition = "0 0";
                } else if (inputs[b].type == "radio" && inputs[b].checked == true && inputs[b].className == "styled") {
                    inputs[b].previousSibling.style.backgroundPosition = "0 -" + radioHeight * 2 + "px";
                } else if (inputs[b].type == "radio" && inputs[b].className == "styled") {
                    inputs[b].previousSibling.style.backgroundPosition = "0 0";
                }
            }
        },
        choose: function () {
            var option = this.getElementsByTagName("option");
            for (var d = 0; d < option.length; d++) {
                if (option[d].selected == true) {
                    document.getElementById("select" + this.name).childNodes[0].nodeValue = option[d].childNodes[0].nodeValue;
                }
            }
        }
    };

    var $$ = function (id, node) {
        if (id && id.length > 0) {
            var s = id.substr(0,1);
            var sId = id.substr(1);
            if (!node) node = document;
            if (s == ".") return $$.GetElementsByClassName(sId, node);
            if (s == "#") return document.getElementById(sId);
            return node.getElementsByTagName(id);
        }
        return null;
    };

    $$.GetStyle = function (obj, prop) {
        var res = null;
        if (window.getComputedStyle) {
            res = window.getComputedStyle(obj, null)[prop];
        } else if (obj.currentStyle) {
            res = obj.currentStyle[prop];
        }
        return res;
    };

    $$.GetInnerWidth = function (elem) {
        var lp = $$.GetStyle(elem, "paddingLeft");
        var rp = $$.GetStyle(elem, "paddingRight");
        lp = lp ? parseInt(lp) : 0;
        rp = rp ? parseInt(rp) : 0;
        return elem.offsetWidth > 0 ? elem.offsetWidth - lp - rp : 0;
    };

    $$.GetElementsByClassName = function (className, node) {
        if (!node) node = document.body;
        var allElements = $$("*", node);
        var results = [];

        var element;
        for (var i = 0; (element = allElements[i]) != null; i++) {
            if ($$.HasClassName(element, className))
                results.push(element);
        }
        return results;
    };

    $$.HasClassName = function (nodeClassNameOrNode, searchClassName) {
        if (!nodeClassNameOrNode)
            return false;
        if (typeof (nodeClassNameOrNode) != 'string')
            nodeClassNameOrNode = nodeClassNameOrNode.className;
        var hasClassName = new RegExp("(?:^|\\s)" + searchClassName + "(?:$|\\s)");
        if (nodeClassNameOrNode && nodeClassNameOrNode.indexOf(searchClassName) != -1 && hasClassName.test(nodeClassNameOrNode))
            return true;
        return false;
    };

    $$.AddClassName = function (nodes, className) {
        if (typeof (nodes) == 'array' || (nodes.length || nodes.length == 0) && nodes.tagName != 'SELECT') {
            for (var i = 0; i < nodes.length; i++)
                $$.AddClassName(nodes[i], className);
            return;
        }
        if (!$$.HasClassName(nodes, className)) {
            if (!nodes.className)
                nodes.className = className;
            else {
                var oldClassName = $$.TrimAndNormalize(nodes.className);
                className = $$.TrimAndNormalize(className);
                nodes.className = oldClassName + ' ' + className;
            }
        }
    };

    $$.TrimAndNormalize = function (str) {
        if (!str) return;
        return str.replace(/^\s*/, '').replace(/\s*$/, '').replace(/\s{2,}/,' ');
    };

    $$.RemoveClassName = function (nodes, className) {
        if (typeof (nodes) == 'array' || (nodes.length || nodes.length == 0) && nodes.tagName != 'SELECT') {
            for (var i = 0; i < nodes.length; i++)
                $$.RemoveClassName(nodes[i], className);
            return;
        }
        if ($$.HasClassName(nodes, className)) {
            var classNameExp = new RegExp("(?:^|\\s)" + className + "(?:$|\\s)");
            nodes.className = $$.TrimAndNormalize(nodes.className.replace(classNameExp, ' '));
        }
    };

    $$.AddEvent = function (elem, evType, fn) {
        if (typeof (elem) == 'array' || elem.length) {
            var fns = [];
            for (var i = 0; i < elem.length; i++)
                fns.push($$.AddEvent(elem[i], evType, fn));
            return fns;
        }
        if (elem.addEventListener) {
            elem.addEventListener(evType, fn, false);
            return fn;
        }
        else {
            var iefn = function () {
                fn.call(elem);
            };
            elem.attachEvent('on' + evType, iefn);
            return iefn;
        }
    };

    $$.SubmitForm = function (el) {
        if (!el)
            return false;
        if (el.tagName == 'FORM')
            el.submit();
        else
            return $$.SubmitForm(el.parentNode)
        return false;
    };

    $$.ImgLazyLoad = function (el) {
        if(!el || !el.onload)
            return;
        var imgPath = el.onload();
        el.onload = null;
        el.src = imgPath;
    };